package org.lzfto.flink.demo.system.security.service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.lzfto.flink.demo.common.result.PubResult;
import org.lzfto.flink.demo.system.security.entity.LoginData;
import org.lzfto.flink.demo.system.security.entity.LoginTryLog;
import org.lzfto.flink.demo.system.security.entity.SysUser;
import org.lzfto.flink.demo.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

@Lazy
@Service
public class SysUserService {
	
	private final  Logger LOGGER=LoggerFactory.getLogger(getClass());
	
    private JdbcTemplate jdbcTemplate;
    
    private List<SysUser> ALL_USERS;
    private Map<String,LoginTryLog> USER_TRY_LOG;

    public SysUserService() {
        this.USER_TRY_LOG=new HashMap<String,LoginTryLog>();
    }
    
    
    public  List<SysUser> getAllUsers(){
    	return this.ALL_USERS;
    }

    // 创建用户
    public int createUser(SysUser user) {
        String sql = "INSERT INTO sys_user (login_name, password) VALUES (?, md5(?))";
        return jdbcTemplate.update(sql, 
            user.getLoginName(),user.getPassword());
    }

    // 删除用户
	public int deleteUser(int id) {
	    String sql = "DELETE FROM sys_user WHERE id = ?";
	    return jdbcTemplate.update(sql, id);
	}

	private SysUser findByLoginName(String loginName) {
		if (ALL_USERS==null || ALL_USERS.size()==0) {
			LOGGER.error("系统尚未初始化用户或者数据源");
			return null;
		}
		for(SysUser user:ALL_USERS) {
			if (user.getLoginName().equals(loginName)) {
				return user;
			}
		}
		return null;
	}


	// 根据ID查询用户
    public SysUser getUserById(int id) {
        String sql = "SELECT id,login_name,password,last_optime FROM sys_user WHERE id = ?";
        RowMapper<SysUser> rowMapper=new BeanPropertyRowMapper<>(SysUser.class);
        try {
        	SysUser user = jdbcTemplate.queryForObject(sql, rowMapper,id);        
        	return user;
        }
        catch(Exception e) {
        	return null;
        }
    }
    
    public List<SysUser> getAll(){
    	String sql="select id,login_name,password,last_optime from sys_user";
    	RowMapper<SysUser> rowMapper=new BeanPropertyRowMapper<>(SysUser.class);
    	return this.jdbcTemplate.query(sql, rowMapper);
    }
    
    private String getMd5(String password)  {
    	MessageDigest md=null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			LOGGER.error(e.getMessage());
			return null;
		}
        byte[] hashBytes = md.digest(password.getBytes());
        // 转换为十六进制字符串（标准输出格式）
        StringBuilder hexString = new StringBuilder();
        for (byte b : hashBytes) {
            hexString.append(String.format("%02x", b));
        }
        
        return  hexString.toString();
    }

    @SuppressWarnings("unused")
	private LoginTryLog getTry(String loginName) {
		if (this.USER_TRY_LOG.size()==0) {
			return null;
		}
		
		LoginTryLog tryLog=this.USER_TRY_LOG.get(loginName);
		if (tryLog==null) {
			tryLog=new LoginTryLog(loginName,null,0);
		}
		
		return tryLog;
		
	}


	// 根据登录名查询用户
    public  SysUser getUserByLoginName(String loginName) {
        String sql = "SELECT id,login_name,password,last_optime FROM sys_user WHERE login_name = ?";
        RowMapper<SysUser> rowMapper=new BeanPropertyRowMapper<>(SysUser.class);
        try {
        	SysUser user = jdbcTemplate.queryForObject(sql, rowMapper,loginName);        
        	return user;
        }
        catch(Exception e) {
        	return null;
        }
    }
    
    
    public  SysUser getUserByToken(String token) {
    	if (this.ALL_USERS==null || this.ALL_USERS.size()==0) {
    		return null;
    	}
    	
    	for (SysUser user:ALL_USERS) {
    		if (user.getToken()!=null && user.getToken().equals(token)) {
    			return user;
    		}
    	}
    	return null;
    }
    
    
    public void init() {
    	this.jdbcTemplate=SpringUtils.getBean(JdbcTemplate.class);
    	this.refreshUsers();
    }
    
    public boolean isAuthenticated(String token) {
    	if (this.ALL_USERS==null || this.ALL_USERS.size()==0) {
    		return false;
    	}
    	
    	for (SysUser user:ALL_USERS) {
    		if (user.getToken()!=null && user.getToken().equals(token)) {
    			return true;
    		}
    	}
    	return false;
    }
    
    public PubResult<String> login(LoginData loginData){
    	SysUser user=this.findByLoginName(loginData.getLoginName());
    	if(user==null) {
    		return PubResult.error("账户或者密码错误");
    	}
    	
    	String encPassword=this.getMd5(loginData.getPassword());
    	
    	if (user.getPassword().equals(encPassword)) {
    		String token=UUID.randomUUID().toString();
    		user.setToken(token);
    		return PubResult.ok_data(token);
    	}
    	else {
    		return PubResult.error("账户或者密码错误");
    	}
    }
    
    public PubResult<String> logout(String token){
    	SysUser user=this.getUserByToken(token);
    	if(user==null) {
    		return PubResult.ok("成功");
    	}
    	
        user.setToken(null);
        return PubResult.ok("成功");
    }

    public void refreshUsers() {
		this.ALL_USERS=this.getAll();
	}


	// 更新用户信息
    public int updateUser(SysUser user) {
        String sql = "UPDATE sys_user SET login_name = ?, password = md5(?) WHERE id = ?";
        return jdbcTemplate.update(sql,
            user.getLoginName(),
            user.getPassword(),
            user.getId());
    }

    // 验证用户密码
    public boolean validatePassword(String loginName, String rawPassword) {
        String sql = "SELECT count(*) FROM sys_user WHERE login_name = ? and password=md5(?) ";
        Integer cnt = jdbcTemplate.queryForObject(sql, Integer.class, loginName);
        return cnt>0;
    }
    
    
}
